package com.yzdbx.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yzdbx.task.ProductPlanRunnable.GEN_PRODUCT_PLAN_IDS;
import static com.yzdbx.task.SalefOrderRunnable.GEN_ORDER_IDS;
import static com.yzdbx.utils.DbUtil.getMaxId;
import static com.yzdbx.utils.GenUtil.CUR_TIME_STAMP;
import static com.yzdbx.utils.GenUtil.getNo;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: TODO
 * @Version: 1.0
 */
@SuppressWarnings("all")
public class ProductOrderRunnable implements Exe {


    private Connection connection;

    public static final ThreadLocal<List<Integer>> GEN_PRODUCT_ORDER_IDS = new ThreadLocal<>() {
        @Override
        protected List<Integer> initialValue() {
            return new ArrayList<>();
        }
    };

    public static final ThreadLocal<List<Integer>> GEN_LLD_IDS = new ThreadLocal<>() {
        @Override
        protected List<Integer> initialValue() {
            return new ArrayList<>();
        }
    };


    public ProductOrderRunnable(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(int count) throws SQLException {
        //生产计划 ---> 生产工单
        List<Integer> planIds = GEN_PRODUCT_PLAN_IDS.get();

        if (CollectionUtil.isEmpty(planIds)) return Boolean.FALSE;

        List<Integer> orderIds = new ArrayList<>();
        List<Integer> lldIds = new ArrayList<>();
        PreparedStatement statement1 = connection.prepareStatement("select * from corp_member");
        List<String> members = DbUtil.resultSetToList(statement1.executeQuery()).stream().map(map -> map.get("memberId").toString()).toList();

        int rwId = getMaxId(connection, "missionInformationSc02");
        int num = 0;
        int num1 = 0;
        int num2 = 0;
        int num3 = 0;

        //查询工艺价格
        PreparedStatement preparedStatement = connection.prepareStatement("select * from processBasicTables");

        Map<String, BigDecimal> collect = DbUtil.resultSetToList(preparedStatement.executeQuery()).stream().collect(Collectors.toMap(cur -> cur.get("processName").toString(), cur -> ((BigDecimal) cur.get("unitPrice"))));

        int lldId = getMaxId(connection, "itsACollarList");
        int lldxqId = getMaxId(connection, "checklistOfTheCollar");
        for (Integer planId : planIds) {
            Map<String, Object> productPlan = DbUtil.getById(connection, "sc01ProductionPlan", planId);

            PreparedStatement statement = connection.prepareStatement("insert into missionInformationSc02(id,missionStream,productName,otherOrganiser,endOfSchedule,dateOfDelivery,numberOfTasks,numberCompleted,officerincharge,productionPlan,taskStatus,typeOfWorksheet,synchronisingFolderFailedSS,created,actualEndDate,f271) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            statement.setInt(1, ++rwId);
            orderIds.add(rwId);
            statement.setString(2, GenUtil.getNoFromTable(connection, "RW", "missionInformationSc02", "missionStream"));
            statement.setInt(3, ((int) productPlan.get("productInformation")));
            statement.setDate(4, ((Date) productPlan.get("dateOfDelivery")));
            statement.setDate(5, ((Date) productPlan.get("dateOfDelivery")));
            statement.setDate(6, ((Date) productPlan.get("dateOfDelivery")));
            statement.setBigDecimal(7, ((BigDecimal) productPlan.get("number")));
            statement.setBigDecimal(8, ((BigDecimal) productPlan.get("number")));
            statement.setString(9, productPlan.get("synchronisingFolderFailedSS").toString());
            statement.setInt(10, planId);
            statement.setString(11, "未开始");
            statement.setString(12, "存储内容2");
            statement.setString(13, productPlan.get("synchronisingFolderFailedSS").toString());
            statement.setTimestamp(14, ((Timestamp) productPlan.get("created")));
            statement.setDate(15, ((Date) productPlan.get("dateOfDelivery")));
            statement.setString(16, "已排程");
            statement.execute();

            //生产工单领料单
            statement = connection.prepareStatement("insert into itsACollarList (id,theCollarNumber,associatedProducts,productionTasks,f775,theLeadman,associatedOrders,numberToBeProduced) values (?,?,?,?,?,?,?,?)");
            statement.setInt(1, ++lldId);
            lldIds.add(lldId);
            statement.setString(2, GenUtil.getNoFromTable(connection, "LL", "itsACollarList", "theCollarNumber"));
            statement.setInt(3, ((int) productPlan.get("productInformation")));
            statement.setInt(4, rwId);
            statement.setDate(5, ((Date) productPlan.get("dateOfDelivery")));
            statement.setString(6, productPlan.get("synchronisingFolderFailedSS").toString());
            statement.setInt(7, planId);
            statement.setBigDecimal(8, ((BigDecimal) productPlan.get("number")));
            statement.execute();
            //生产领料单明细
            statement = connection.prepareStatement("select * from productBomTable where rawMaterials = ?");
            statement.setInt(1, ((int) productPlan.get("productInformation")));
            List<LinkedHashMap<String, Object>> lldList = DbUtil.resultSetToList(statement.executeQuery());
            BigDecimal total = BigDecimal.ZERO;
            for (LinkedHashMap<String, Object> lld : lldList) {
                statement = connection.prepareStatement("insert into checklistOfTheCollar (id,f8d0,materialInformation,number)values (?,?,?,?)");
                statement.setInt(1, ++lldxqId);
                statement.setInt(2, lldId);
                statement.setInt(3, ((int) lld.get("rawMaterials1")));
                BigDecimal quantity = ((BigDecimal) lld.get("number")).multiply(((BigDecimal) productPlan.get("number"))).setScale(2, BigDecimal.ROUND_HALF_UP);
                statement.setBigDecimal(4, quantity);
                statement.execute();
                total = total.add(quantity);
            }
            //更新领料单总数量
            statement = connection.prepareStatement("update itsACollarList set totalNumber = ? where id = ?");
            statement.setBigDecimal(1, total);
            statement.setInt(2, lldId);
            statement.execute();
            //查询产品工艺路线
            statement = connection.prepareStatement("select * from gy0501ProcessProcessSubtable where associatedProductLibrary = ? order by id asc");
            statement.setInt(1, ((int) productPlan.get("productInformation")));
            List<LinkedHashMap<String, Object>> gylxList = DbUtil.resultSetToList(statement.executeQuery());

            int gyId = getMaxId(connection, "sctechMissions");
            int bgId = getMaxId(connection, "checklistSc05");
            for (LinkedHashMap<String, Object> gylx : gylxList) {
                //工单生成工艺任务
                statement = connection.prepareStatement("insert into sctechMissions (id,craftFlowNumber,associatedTasks,processName,serialNumber,productInformation,dateOfDelivery,plannedEndDate,numberOfTasks,numberCompleted,mandatedPersons,routineStatus)values (?,?,?,?,?,?,?,?,?,?,?,?)");
                statement.setInt(1, ++gyId);
                statement.setString(2, GenUtil.getNoFromTable(connection, "GY", "sctechMissions", "craftFlowNumber"));
                statement.setInt(3, rwId);
                statement.setString(4, gylx.get("f7ff").toString());
                statement.setInt(5, ((int) gylx.get("id")));
                statement.setInt(6, ((int) productPlan.get("productInformation")));
                statement.setDate(7, ((Date) productPlan.get("dateOfDelivery")));
                statement.setDate(8, ((Date) productPlan.get("dateOfDelivery")));
                statement.setBigDecimal(9, ((BigDecimal) productPlan.get("number")));
                statement.setBigDecimal(10, ((BigDecimal) productPlan.get("number")));
                statement.setString(11, productPlan.get("synchronisingFolderFailedSS").toString());
                statement.setString(12, "存储内容2");
                statement.execute();

                //生成报工明细
                statement = connection.prepareStatement("insert into  checklistSc05 (id,wellCallTheFactoryStreamer,linkProcessTasks,associatedProductionTasks,productInformation,processName,dateOfReport,numberOfTasks,numberOfCompleted,numberOfReporters,numberOfEndoflifeWarranties,reportingStaff,auditStatus,unitPrice,synchronisingFolderFailedSS,created,modifyer,modified) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                statement.setInt(1, ++bgId);
                statement.setString(2, GenUtil.getNoFromTable(connection, "BG", "checklistSc05", "wellCallTheFactoryStreamer"));
                statement.setInt(3, gyId);
                statement.setInt(4, rwId);
                statement.setInt(5, ((int) productPlan.get("productInformation")));
                statement.setString(6, gylx.get("f7ff").toString());
                statement.setDate(7, ((Date) productPlan.get("dateOfDelivery")));
                statement.setBigDecimal(8, ((BigDecimal) productPlan.get("number")));
                //随机完成数量
                BigDecimal bigDecimal = RandomUtil.randomBigDecimal(BigDecimal.ONE, ((BigDecimal) productPlan.get("number")));
                statement.setBigDecimal(9, bigDecimal);
                statement.setBigDecimal(10, bigDecimal);
                statement.setBigDecimal(11, BigDecimal.ZERO);
                statement.setString(12, RandomUtil.randomEle(members));
                statement.setString(13, "已审核");
                statement.setBigDecimal(14, collect.get(gylx.get("f7ff").toString()));
                statement.setString(15, productPlan.get("synchronisingFolderFailedSS").toString());
                statement.setTimestamp(16, ((Timestamp) productPlan.get("created")));
                statement.setString(17, productPlan.get("synchronisingFolderFailedSS").toString());
                statement.setTimestamp(18, ((Timestamp) productPlan.get("created")));
                statement.execute();
            }
        }
        GEN_PRODUCT_ORDER_IDS.set(orderIds);
        GEN_LLD_IDS.set(lldIds);
        return Boolean.TRUE;
    }


}
